﻿using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;

namespace GBricks
{
  [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Optional", Justification = Justifications.ConvenientIdentifier)]
  public static class Optional
  {
    public static Optional<T> Create<T>(T value) {
      return new Optional<T>(value);
    }

    public static Optional<T> FromNullable<T>(T value) where T : class {
      return value != null ? Create(value) : default(Optional<T>);
    }

    public static Optional<T> FromNullable<T>(T? value) where T : struct {
      return value.HasValue ? Create(value.Value) : default(Optional<T>);
    }

    public static TValue GetValueOrDefault<TValue>(this Optional<TValue> optional, TValue defaultValue = default(TValue)) {
      return optional.HasValue ? optional.Value : defaultValue;
    }
  }
}
